package com.hospital.hospitalserver.service;

import com.hospital.hospitalserver.entity.NurseDetail;
import com.hospital.hospitalserver.entity.UserInfo;
import com.hospital.hospitalserver.entity.Vo.Nurse;
import com.hospital.hospitalserver.mapper.DepartmentMapper;
import com.hospital.hospitalserver.mapper.NurseMapper;
import com.hospital.hospitalserver.mapper.UserMapper;
import com.hospital.hospitalserver.util.EncryptHelper;
import com.hospital.hospitalserver.util.Pager;
import com.hospital.hospitalserver.util.PagerData;
import com.hospital.hospitalserver.util.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 护士管理相关实现方法
 * */
@Service
@RequiredArgsConstructor
public class NurseService {
    private final NurseMapper nurseMapper;
    private final UserMapper userMapper;
    private final DepartmentMapper departmentMapper;

    /**
     * 新增护士
     * 添加事务处理，执行有错误回滚操作
     * */
    @Transactional(rollbackFor = Exception.class)
    public Response addNurse(NurseDetail nurse){
        // 1.判断添加的账户是否存在重复
        UserInfo u = userMapper.findUserByUsername(nurse);
        if(u!=null){
            return Response.error("账户名已存在");
        }

        // 2. 设置默认角色（例如护士角色 role_id = 2）
        nurse.setRole_id(2); // 根据实际角色ID设置
        nurse.setIs_active(1); // 默认激活
        String encryptedPassword = EncryptHelper.SHA(nurse.getUserpass());
        nurse.setUserpass(encryptedPassword);

        // 3. 添加用户，此时 nurse 对象的 user_id 会被自动填充
        Integer addCount = userMapper.addUser(nurse);
        if(addCount==0){
            return Response.error("用户添加失败");
        }

        // 4. 此时 nurse.getUser_id() 已经包含新生成的 user_id
        nurse.setNurse_id(nurse.getUser_id()); // 共享主键

        // 5. 添加护士详细信息
        Integer count = nurseMapper.addNurse(nurse);
        if(count > 0){
            //添加成功则更新对应科室护士总数
            departmentMapper.UpdateAddNurseCountByDepartmentId(nurse.getDepartment_id());
            return Response.success();
        }else {
            return Response.error("护士信息添加失败");
        }
    }

    /**
     * 编辑护士信息
     * 添加事务处理，执行有错误回滚操作
     * */
    @Transactional(rollbackFor = Exception.class)
    public Response editNurse(NurseDetail nurse){
        // 1.取出护士数据信息
        Nurse nurseInfo = nurseMapper.findByNurseId(nurse.getNurse_id());

        Integer counts = nurseMapper.editNurse(nurse);
        if(counts>0){
            //编辑成功之后判断是否更换了科室，如果更换科室要同步更新各个科室的护士人数
            // 2. 比对科室信息是否有修改
            if(!nurse.getDepartment_id().equals(nurseInfo.getDepartment_id())){
                //变更科室
                //减少原科室护士人数
                departmentMapper.UpdateDeleteNurseCountByDepartmentId(nurseInfo.getDepartment_id());
                //增加新科室护士人数
                departmentMapper.UpdateAddNurseCountByDepartmentId(nurse.getDepartment_id());
            }
            return Response.success();
        }else{
            return Response.error();
        }
    }

    /**
     * 分页功能
     * 根据搜索条件查询护士数据总数
     * */
    private Integer getNurseCountBySearch(Pager pager){
        return nurseMapper.getNurseCountBySearch(pager);
    }

    /**
     * 计算分页
     * */
    private Integer getNursePageTotalBySearch(Pager pager){
        Integer nurseTotalCounts = getNurseCountBySearch(pager);
        Integer pageTotal = 1;//设置初始页码为1
        //数据总条数除以pageSize每页显示条数，如取余数求模，如果有余数，页码+1
        //如果可以整除，则页码等于数据总数除以pageSize
        pageTotal = nurseTotalCounts/pager.getPageSize();
        if(nurseTotalCounts% pager.getPageSize()>0){
            pageTotal += 1;
        }
        return pageTotal;
    }

    /**
     * 分页功能
     * 根据搜索条件查询护士分页数据
     * */
    private List<Nurse> getNurseMapperDataBySearch(Pager pager){
        Integer currentPage = pager.getCurrentPage();
        Integer startIndex = (currentPage - 1)*pager.getPageSize();
        pager.setStartIndex(startIndex);
        return nurseMapper.getNurseMapperDataBySearch(pager);
    }

    /**
     * 分页功能
     * 装载护士分页数据信息给前端API
     * */
    public Response getNursePagerDataBySearch(Pager pager){
        PagerData pagerData = new PagerData();
        pagerData.setTotal(getNurseCountBySearch(pager));
        pagerData.setPageTotal(getNursePageTotalBySearch(pager));
        pagerData.setData(getNurseMapperDataBySearch(pager));
        return Response.success(pagerData);
    }

    /**
     * 获取护士的列表数据
     * 用于查询检索
     * */
    public Response getNurseList(){
        return Response.success(nurseMapper.getNurseList());
    }
}
